package personal.dao.accounting;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import personal.domain.accounting.MonthwiseCalendar;


@Repository
public class MonthwiseCalendarDAOImpl implements MonthwiseCalendarDAO {
	
	@PersistenceContext(unitName="accountingPU")
	private EntityManager em;

	@Override
	public MonthwiseCalendar saveMonthlyCalendar(MonthwiseCalendar calendar) {
		return em.merge(calendar);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<MonthwiseCalendar> getMonthwiseCalendars(MonthwiseCalendar calendar) {
		Query query;
		if (calendar.getMonth() == null) {
			query = em.createNamedQuery(MonthwiseCalendar.MONTHWISE_CAL_GET_ALL_FOR_YEAR);
		} else {
			query = em.createNamedQuery(MonthwiseCalendar.MONTHWISE_CAL_GET_FOR_MONTH);
			query.setParameter("month", calendar.getMonth());
		}
		query.setParameter("year", calendar.getYear());
		return query.getResultList();
	}

	@Override
	public List<Long> getMonthwiseCalendarIds(List<MonthwiseCalendar> calendars) {
		List<Long> calendarIds = new ArrayList<Long>();
		for (int i = 0; i < calendars.size(); i++) {
			calendarIds.add(calendars.get(i).getCalendarId());
		}
		return calendarIds;
	}
}
